using System;
using System.Linq;
using Iesi.Collections.Generic;

namespace Headspring.Training.Core.Model
{
	public class WorkOrder
	{
		private readonly ISet<HistoryEntry> _history =
			new HashedSet<HistoryEntry>();

		public WorkOrder()
		{
			Description = "";
			Status = WorkOrderStatus.Draft;
			Title = "";
			Facility = new Facility();
		}

		public virtual Guid Id { get; set; }
		public virtual string Title { get; set; }
		public virtual string Description { get; set; }
		public virtual WorkOrderStatus Status { get; set; }
		public virtual Employee Creator { get; set; }
		public virtual Employee Assignee { get; set; }
		public virtual DateTime? CreatedDate { get; set; }
		public virtual DateTime? CompletedDate { get; set; }
		public virtual DateTime? LastChangeDate { get; private set; }
		public virtual string Number { get; set; }
		public virtual Facility Facility { get; set; }
		public virtual int HistoryLength { get; set; }

		public virtual string FriendlyStatus
		{
			get { return getTextForStatus(); }
		}

		protected virtual string getTextForStatus()
		{
			return Status.ToString();
		}

		public override string ToString()
		{
			return "Work Order " + Number;
		}

		public virtual void ChangeStatus(WorkOrderStatus status, Employee currentUser,
		                                 DateTime changeDate)
		{
			AddHistory(new HistoryEntry(currentUser, Status, status, changeDate));
			Status = status;
		}

		public virtual void AddHistory(HistoryEntry entry)
		{
			_history.Add(entry);
		}

		public virtual HistoryEntry[] GetHistory()
		{
			HistoryEntry[] historyEntries = _history.ToArray();
			Array.Sort(historyEntries, (x, y) => y.ChangeDate.CompareTo(x.ChangeDate));
			return historyEntries;
		}
	}
}